package business_opportunity

import (
	"context"
	"fmt"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto"
	reportDto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/oppty/report"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/clue"
	"strings"
)

type ReportRepository struct {
}

func NewReportRepository() ReportRepositoryIface {
	return &ReportRepository{}
}

func (r *ReportRepository) SearchContacts(ctx context.Context, params *reportDto.SearchContactRequest) (*http_client.BigDataResponse, error) {
	resultData := &http_client.BigDataResponse{}
	header := map[string]string{}

	if params.PageSize == 0 {
		params.PageSize = 10
	}
	bigdataParamsMap, err := simplecopier.StructToMapByJsonTag(params)
	if err != nil {
		return resultData, err
	}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.SearchContacts, bigdataParamsMap, header).EndStruct(&resultData)
	if errs != nil {
		return nil, errs[0]
	}

	return resultData, nil
}

// Save 保存报备信息
func (r *ReportRepository) Save(ctx context.Context, params map[string]interface{}) (bool, error) {
	request := &pb.SaveReportRequest{
		ReportSourceType:        "DIRECT", //PC端只有直接报备的来源类型
		ReportSourceId:          "",       //分享类型才需要填ID
		ClueSource:              r.getMapValue("clue_source", params),
		ClueSourceId:            r.getMapValue("clue_source_id", params),
		CompanyName:             r.getMapValue("company_name", params),
		CompanyOrganizingCode:   r.getMapValue("company_organizing_code", params),
		CompanyType:             r.getMapValue("company_type", params),
		CompanyCityCode:         r.getMapValue("company_city_code", params),
		CompanyCity:             r.getMapValue("company_city", params),
		CompanyProvinceCode:     r.getMapValue("company_province_code", params),
		CompanyProvince:         r.getMapValue("company_province", params),
		DefaultContact:          r.getMapValue("default_contact", params),
		DefaultContactTel:       r.getMapValue("default_contact_tel", params),
		ContactPosition:         r.getMapValue("contact_position", params),
		ProjectTitle:            r.getMapValue("project_title", params),
		ProjectType:             r.getMapValue("project_type", params),
		ProjectAddress:          r.getMapValue("project_address", params),
		ProjectProvinceCode:     r.getMapValue("project_province_code", params),
		ProjectProvince:         r.getMapValue("project_province", params),
		ProjectCityCode:         r.getMapValue("project_city_code", params),
		ProjectCity:             r.getMapValue("project_city", params),
		ProjectImage:            r.getMapValue("project_image", params),
		SubmitterCompany:        r.getMapValue("submitter_company", params),
		Submitter:               r.getMapValue("submitter", params),
		SubmitterTel:            r.getMapValue("submitter_tel", params),
		AgencyName:              r.getMapValue("agency_name", params),
		AgencyContact:           r.getMapValue("agency_contact", params),
		AgencyContactTel:        r.getMapValue("agency_contact_tel", params),
		ResponsiblePersonGuid:   r.getMapValue("responsible_person_guid", params),
		ResponsiblePersonName:   r.getMapValue("responsible_person_name", params),
		TemplateId:              r.getMapValue("template_id", params),
		ResponsiblePersonMobile: r.getMapValue("responsible_person_mobile", params),
	}
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return false, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewReportServiceClient(conn)
	resp, err := client.SaveReport(ctx, request)
	if err != nil {
		return false, err
	}
	return resp.IsSuccess, nil
}

func (r *ReportRepository) getMapValue(key string, params map[string]interface{}) string {
	if value, ok := params[key]; ok {
		switch v := value.(type) {
		case string:
			return v
		case []interface{}:
			strList := make([]string, len(v))
			for i, item := range v {
				fmt.Println(item)
				if str, ok := item.(string); ok {
					strList[i] = str
				}
			}
			return strings.Join(strList, ",")
		default:
			return fmt.Sprintf("%v", value)
		}
	}
	return ""
}

// GetReportSourceInfo 报备来源的附带信息
func (r *ReportRepository) GetReportSourceInfo(ctx context.Context, sourceType, sourceId string) (map[string]interface{}, error) {
	request := &pb.GetReportSourceInfoRequest{
		ReportSourceType: sourceType,
		ReportSourceId:   sourceId,
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewReportServiceClient(conn)
	resp, err := client.GetReportSourceInfo(ctx, request)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, nil
	}

	result, err := simplecopier.StructToMapByJsonTag(resp)
	if err != nil {
		return nil, err
	}

	if value, ok := result["project_image"]; ok && value.(string) != "" {
		result["project_image"] = strings.Split(value.(string), ",")
	} else {
		result["project_image"] = make([]string, 0)
	}

	return result, nil
}

func (r *ReportRepository) GetReportList(ctx context.Context, request *dto.ReportMyListRequestDto) (*pb.GetReportListResponse, error) {
	params := &pb.GetReportListRequest{
		ResponsiblePersonGuid: authorize.GetTenantUserId(ctx),
		Keyword:               request.Keyword,
		ProjectProvinceCode:   request.ProjectProvinceCode,
		ProjectCityCode:       request.ProjectCityCode,
		CompanyProvinceCode:   request.CompanyProvinceCode,
		CompanyCityCode:       request.CompanyCityCode,
		SubmitStartTime:       request.SubmitStartTime,
		SubmitEndTime:         request.SubmitEndTime,
		FollowStatus:          int32(request.FollowStatus),
		Page:                  int32(request.Page),
		PageSize:              int32(request.PageSize),
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewReportServiceClient(conn)
	return client.GetReportList(ctx, params)
}

func (r *ReportRepository) GetRegionReportList(ctx context.Context, request *dto.ReportMyListRequestDto) (*pb.GetReportListResponse, error) {
	params := &pb.GetReportListRequest{
		UserId:                authorize.GetTenantUserId(ctx),
		ResponsiblePersonGuid: request.ResponsiblePersonGuid,
		Keyword:               request.Keyword,
		ProjectProvinceCode:   request.ProjectProvinceCode,
		ProjectCityCode:       request.ProjectCityCode,
		CompanyProvinceCode:   request.CompanyProvinceCode,
		CompanyCityCode:       request.CompanyCityCode,
		SubmitStartTime:       request.SubmitStartTime,
		SubmitEndTime:         request.SubmitEndTime,
		FollowStatus:          int32(request.FollowStatus),
		Page:                  int32(request.Page),
		PageSize:              int32(request.PageSize),
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewReportServiceClient(conn)

	return client.GetRegionReportList(ctx, params)
}

func (r *ReportRepository) GetReport(ctx context.Context, reportId string) (*pb.GetReportResponse, error) {
	request := pb.GetReportRequest{
		ReportId: reportId,
	}
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewReportServiceClient(conn)
	return client.GetReport(ctx, &request)
}

func (r *ReportRepository) GetTeamLeader(ctx context.Context, reportId string) (map[string]interface{}, error) {
	request := &pb.GetTeamLeaderRequest{
		ReportUid: reportId,
	}
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewReportServiceClient(conn)
	resp, err := client.GetTeamLeader(ctx, request)
	if err != nil {
		return nil, err
	}
	result, err := simplecopier.StructToMapByJsonTag(resp)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (r *ReportRepository) GetUserList(ctx context.Context) (map[string]interface{}, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewReportServiceClient(conn)
	resp, err := client.GetUserList(ctx, &pb.GetUserListRequest{})
	if err != nil {
		return nil, err
	}

	result, err := simplecopier.StructToMapByJsonTag(resp)
	if err != nil {
		return nil, err
	}

	return result, nil
}
